package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {

    //依赖注入
    @Autowired
    private EmpService empService;


    /**
     * 用户登录
     *
     * @param emp
     * @return
     */
    @PostMapping
    public Result login(@RequestBody Emp emp){
        //日志
        log.info("用户登录：{}",emp);
        //调用应用层
        Emp e = empService.login(emp);
        //判断，并统一返回结果
        if (e != null){
            //集合封装自定义内容
            Map<String,Object> map = new HashMap<>();
            map.put("id",e.getId());
            map.put("username",e.getUsername());
            map.put("name",e.getName());
            //生成jwt令牌
            String jwt = JwtUtils.generateJwt(map);
            //将令牌响应到前端
            return Result.success(jwt);
        }else {
            return Result.error("用户名或密码错误");
        }
    }
}
